package com.xuecheng.content.service.impl;


import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {


    /*
     * 课程分类查询(树形的递归查询)
     * */
    @Autowired
    private CourseCategoryMapper courseCategoryMapper;

    /*
     * 思路：先去查询，将查询到的数据遍历插入到父节点的ChildrenTreeNodes中
     * 1，查询 2，转成map便于我们查找子节点，key就是id，value就是value
     * 3一边遍历一边查找，4插入数据
     * */

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //先去查询,
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        //转成map
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().
                filter(item->!id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));

        ArrayList<CourseCategoryTreeDto> categoryList = new ArrayList<>();


        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach( item ->{
            if (item.getParentid().equals(id))
            {
                categoryList.add(item);
            }

            CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());

            if (courseCategoryParent != null)
            {
                if (courseCategoryParent.getChildrenTreeNodes() == null)
                {

                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }
        });
        return categoryList;
    }
}
